package com.itholmes.tomcat;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import com.itholmes.ServletConfig.ServletConfig;
import com.itholmes.ServletContext.ServletContext;
import com.itholmes.bean.ServletUrlAndClassAndInitparam;

public class MyTomcatThread implements Runnable{

	private Socket socket;
	
	//判断是否包含映射该url
	private static Map<String, String> mapping = new HashMap<String, String>();
	
	//servletContext对象，context域对象 ，因为context的域对象必须是随着app的消亡而消失，所以这里也必须定义跟web.xml文件一致的context域对象。
	private static ServletContext context;
	
	//加载驱动
	static {
		mapping = new MyMapping().getMappingAndClassURL().getUrl_class();
		context = new MyMapping().getServletContext();
	}
	
	public static void driverLoad() {
		//目的就是为了加载一下该类，让mapping拿到xml文件中的键值对。
		System.out.println("加载驱动~");
	}
	
	public MyTomcatThread(Socket socket) {
		this.socket = socket;
	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			
			InputStream in = socket.getInputStream();
			OutputStream out = socket.getOutputStream();
			
			MyRequest req = new MyRequest(in);
			MyResponse resp = new MyResponse(out);
			
			req.setContext(context);
			ServletConfig config = new MyMapping().getMappingAndClassURL().getConfig();
			req.setConfig(config);
			
			String request_url = req.getRequest_url();
			String request_servlet_class_url = "";
			
			Set<Entry<String,String>> entrySet = mapping.entrySet();
			Iterator<Entry<String, String>> iterator = entrySet.iterator();
			while(iterator.hasNext()) {
				Entry<String, String> next = iterator.next();
				if(next.getKey().equals(request_url)) {
					request_servlet_class_url = next.getValue();
				}
			}
			
			if(request_servlet_class_url.equals("")) {
				//响应404，结束该线程
				out.write(new MyResponse(out).notFoundMethod().getBytes());
				in.close();
				out.close();
				return;
			}
			
			//如果有映射的url，反射创建它的对象。
			try {
				Class<?> forName = Class.forName(request_servlet_class_url);
				MyServlet newInstance = (MyServlet)forName.newInstance();
				newInstance.setConfig(config);
				newInstance.service(req, resp);
				in.close();
				return;
			} catch (Exception e) {
				e.printStackTrace();
				//如果抛出异常直接返回500
				resp.serverErrorMethod(e);
			}
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
